package com.xb.loan.encryptor.handler.impl;


import com.xb.loan.encryptor.LotteryException;
import com.xb.loan.encryptor.bean.LotteryBean;
import com.xb.loan.encryptor.bean.request.other.QueryPartnerKeyReq;
import com.xb.loan.encryptor.bean.response.other.QueryPartnerKeyRep;
import com.xb.loan.encryptor.handler.BussinessHandler;
import com.xb.loan.encryptor.util.Const;
import com.xb.loan.encryptor.util.ToolUtil;
import com.xb.loan.util.DateHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.text.ParseException;
import java.util.Date;

public class QueryPartnerKeyHandler implements BussinessHandler {

	private static Log log = LogFactory.getLog(QueryPartnerKeyHandler.class);
	// 密钥的key刷新时间
	private long keyFlushTime = 5 * 60 * 1000;

	@Override
	public LotteryBean doBussiness(LotteryBean lotteryBean)
			throws LotteryException {

		QueryPartnerKeyReq req = (QueryPartnerKeyReq) lotteryBean;

		log.info("QueryPartnerKeyHandler query partner " + req.getPartnerId()
				+ " type:" + req.getKeyType() + " key.");

		String keyPath = createKeyPath(req.getPartnerId(), req.getKeyType());
		// 读取密钥内容
		byte[] dataContent = ToolUtil.fileToBytes(keyPath);
		// 密钥
		String partnerKey = dataContent == null ? null : new String(dataContent);
		
		QueryPartnerKeyRep rep = new QueryPartnerKeyRep();
		
		rep.setHead(LotteryBean.createHead("703", req.getHead().getGuid()));
		try {
			
			rep.setExpirationTime(DateHelper.formatDate("yyyyMMddHHmmss", new Date(DateHelper.convertToDate("yyyyMMddHHmmss", req.getKeyTime()).getTime() + keyFlushTime)));
		} catch (ParseException e) {
			
			log.error("QueryPartnerKeyHandler query partner have exception" + req.getPartnerId()
					+ " type:" + req.getKeyType() + " key.",e);
		}
		rep.setPartnerId(req.getPartnerId());
		rep.setPartnerKey(partnerKey);
		
		return rep;
	}

	private String createKeyPath(String partnerId, String keyType) {
		
		String path = Const.KEY_PATH + File.separatorChar + "partner" + File.separatorChar + partnerId + File.separatorChar;
		
		if (Const.PARTNER_GEN_PUBKEY.equals(keyType)) {
			
			path += "gen" + File.separatorChar + "publicKey.txt";
		} else if (Const.PARTNER_GEN_PRIKEY.equals(keyType)) {
			
			path += "gen" + File.separatorChar + "privateKey.txt";
		} else {
			path += "partnerPubkey.txt";
		}

		return path;
	}

}
